package com.markus.code.剑指offer;

/**
 * Author:markusZhang
 * Date:Create in 2020/8/31 13:26
 * todo: 礼物的最大值
 */
public class MaxValue {
    public int maxValue(int[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0){
            return 0;
        }
//        int[][] dp = getDP(grid);
//        return dp[grid.length-1][grid[0].length-1];
        int[] dp = getDpWithPush(grid);
        return dp[grid[0].length-1];
    }
    private int[][] getDP(int [][]grid){
        int [][]dp = new int[grid.length][grid[0].length];
        //填基本数据
        dp[0][0] = grid[0][0];
        for (int j=1;j<grid[0].length;j++){
            dp[0][j] = dp[0][j-1]+grid[0][j];
        }
        for (int i=1;i<grid.length;i++){
            dp[i][0] = dp[i-1][0]+grid[i][0];
        }
        //填普通数据
        for (int i=1;i<grid.length;i++){
            for (int j=1;j<grid[i].length;j++){
                dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1])+grid[i][j];
            }
        }
        return dp;
    }
    private int[] getDpWithPush(int [][]grid){
        int []dp = new int[grid[0].length];
        dp[0] = grid[0][0];
        for (int i=1;i<dp.length;i++){
            dp[i] = dp[i-1] + grid[0][i];
        }
        for (int i=1;i<grid.length;i++){
            for (int j=0;j<grid[i].length;j++){
                int preValue = j-1>=0?Math.max(dp[j-1],dp[j]):dp[j];
                dp[j] = preValue + grid[i][j];
            }
        }
        return dp;
    }

    public static void main(String[] args) {
        int [][]grid = {{1,3,1},{1,5,1},{4,2,1}};
        MaxValue demo = new MaxValue();
        System.out.println(demo.maxValue(grid));
    }
}
